<template>
  <div class="app-container">
    <!-- 筛选区域 -->
    <div class="filter-container">
      <div class="section-header">
        <i class="el-icon-search"></i>
        <span>筛选条件</span>
      </div>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <!-- 第一行：主要筛选条件 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="任务">
              <el-select
                v-model="queryParams.taskId"
                placeholder="请选择任务"
                @change="onTaskChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in taskList"
                  :key="item.id"
                  :label="item.taskName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="6">
            <el-form-item label="用户账号">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入用户账号"
                @keyup.enter.native="handleQuery"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="6">
            <el-form-item label="用户名称">
              <el-input
                v-model="queryParams.nickName"
                placeholder="请输入用户名称"
                @keyup.enter.native="handleQuery"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="6">
            <el-form-item label="访谈层级">
              <el-select
                v-model="queryParams.level"
                placeholder="请选择访谈层级"
                style="width: 100%"
                clearable>
                <el-option label="一级" value="1"></el-option>
                <el-option label="二级" value="2"></el-option>
                <el-option label="三级" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第二行：详细筛选条件 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="访谈者">
              <el-input
                v-model="queryParams.interviewer"
                placeholder="请输入访谈者"
                @keyup.enter.native="handleQuery"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="访谈时间">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                @change="onDateRangeChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
          
          <el-col :span="6">
            <el-form-item label="访谈状态">
              <el-select
                v-model="queryParams.interviewStatus"
                placeholder="请选择访谈状态"
                style="width: 100%"
                clearable>
                <el-option label="未访谈" value="0"></el-option>
                <el-option label="已访谈" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd">新增</el-button>
      <el-button type="success" plain icon="el-icon-edit" @click="handleUpdate" :disabled="single">修改</el-button>
      <el-button type="danger" plain icon="el-icon-delete" @click="handleDelete" :disabled="multiple">删除</el-button>
      <el-button type="warning" plain icon="el-icon-download" :loading="exportLoading" @click="handleExport">导出</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="recordList"
      @selection-change="handleSelectionChange"
      style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column prop="taskId" label="任务ID" width="80" align="center" />
      <el-table-column prop="userName" label="用户账号" width="120" align="center" />
      <el-table-column prop="nickName" label="用户名称" width="100" align="center" />
      <el-table-column prop="sex" label="性别" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sex === 1 ? '男' : '女' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="grade" label="年级" align="center" />
      <el-table-column prop="classz" label="班级" align="center" />
      <el-table-column prop="school" label="学校" align="center" />
      <el-table-column prop="level" label="访谈层级" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.level" :type="getLevelTagType(scope.row.level)">
            {{ getLevelText(scope.row.level) }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="interviewer" label="访谈者" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.interviewer || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="interviewTime" label="访谈时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.interviewTime || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="interviewResult" label="访谈状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.interviewResult)">
            {{ getStatusText(scope.row.interviewResult) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)">
            修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改访谈记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户账号" disabled />
        </el-form-item>
        <el-form-item label="用户名称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入用户名称" disabled />
        </el-form-item>
        <el-form-item label="访谈层级" prop="level">
          <el-select v-model="form.level" placeholder="请选择访谈层级">
            <el-option label="一级" value="1"></el-option>
            <el-option label="二级" value="2"></el-option>
            <el-option label="三级" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="访谈者" prop="interviewer">
          <el-input v-model="form.interviewer" placeholder="请输入访谈者" />
        </el-form-item>
        <el-form-item label="访谈时间" prop="interviewTime">
          <el-date-picker
            v-model="form.interviewTime"
            type="datetime"
            placeholder="选择访谈时间"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="访谈结果" prop="interviewResult">
          <el-select v-model="form.interviewResult" placeholder="请选择访谈结果">
            <el-option label="未访谈" value="0"></el-option>
            <el-option label="已访谈" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAssess } from "@/api/system/assess";
import { listInterview, getInterview, addInterview, updateInterview, delInterview, exportInterview } from "@/api/system/interview";

export default {
  name: "InterviewRecord",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出加载状态
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 访谈记录表格数据
      recordList: [],
      // 任务列表
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskId: null,
        userName: null,
        nickName: null,
        level: null,
        interviewer: null,
        interviewStatus: null,
        startTime: null,
        endTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        level: [
          { required: true, message: "访谈层级不能为空", trigger: "change" }
        ],
        interviewer: [
          { required: true, message: "访谈者不能为空", trigger: "blur" }
        ],
        interviewTime: [
          { required: true, message: "访谈时间不能为空", trigger: "change" }
        ],
        interviewResult: [
          { required: true, message: "访谈结果不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getTaskList();
  },
  methods: {
    /** 查询任务列表 */
    getTaskList() {
      this.loading = true;
      listAssess({
        pageNum: 1,
        pageSize: 1000
      }).then(response => {
        this.taskList = response.rows || [];
        console.log('任务列表数据:', this.taskList);
        
        // 默认选择第一个任务
        if (this.taskList.length > 0) {
          this.queryParams.taskId = this.taskList[0].id;
          console.log('默认选择任务ID:', this.queryParams.taskId);
          this.getList();
        } else {
          this.loading = false;
        }
      }).catch(error => {
        console.error('获取任务列表失败:', error);
        this.loading = false;
      });
    },
    
    /** 查询访谈记录列表 */
    getList() {
      if (!this.queryParams.taskId) {
        this.loading = false;
        return;
      }
      
      this.loading = true;
      
      // 构建查询参数
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        taskId: this.queryParams.taskId
      };
      
      // 添加筛选条件
      if (this.queryParams.userName) params.userName = this.queryParams.userName;
      if (this.queryParams.nickName) params.nickName = this.queryParams.nickName;
      if (this.queryParams.level) params.level = this.queryParams.level;
      if (this.queryParams.interviewer) params.interviewer = this.queryParams.interviewer;
      if (this.queryParams.interviewStatus) params.interviewStatus = this.queryParams.interviewStatus;
      if (this.queryParams.startTime) params.startTime = this.queryParams.startTime;
      if (this.queryParams.endTime) params.endTime = this.queryParams.endTime;
      
      console.log('查询参数:', params);
      
      // 调用访谈记录接口
      listInterview(params).then(response => {
        this.recordList = response.rows || response.data || [];
        this.total = response.total || this.recordList.length;
        console.log('访谈记录数据:', this.recordList);
        this.loading = false;
      }).catch(error => {
        console.error('获取访谈记录失败:', error);
        this.loading = false;
        this.$message.error('获取访谈记录失败');
      });
    },
    
    /** 任务切换 */
    onTaskChange() {
      console.log('切换任务ID:', this.queryParams.taskId);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    /** 日期范围变化 */
    onDateRangeChange(dates) {
      if (dates && dates.length === 2) {
        this.queryParams.startTime = dates[0];
        this.queryParams.endTime = dates[1];
      } else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      // 保存当前任务ID
      const currentTaskId = this.queryParams.taskId;
      
      this.dateRange = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        taskId: currentTaskId, // 保持任务选择不变
        userName: null,
        nickName: null,
        level: null,
        interviewer: null,
        interviewStatus: null,
        startTime: null,
        endTime: null
      };
      this.handleQuery();
    },
    
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.warnId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加访谈记录";
    },
    
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const warnId = row.warnId || this.ids[0];
      // 获取访谈记录详情
      if (row.id) {
        getInterview(row.id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改访谈记录";
        }).catch(error => {
          console.error('获取访谈记录详情失败:', error);
          this.$message.error('获取访谈记录详情失败');
        });
      } else {
        this.form = Object.assign({}, row);
        this.open = true;
        this.title = "修改访谈记录";
      }
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      const warnIds = row.warnId ? [row.warnId] : this.ids;
      const ids = row.id ? [row.id] : this.ids;
      this.$confirm('是否确认删除选中的访谈记录？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 调用删除接口
        return delInterview(ids.join(','));
      }).then(() => {
        this.$message.success("删除成功");
        this.getList();
      }).catch(error => {
        if (error !== 'cancel') {
          console.error('删除访谈记录失败:', error);
          this.$message.error('删除访谈记录失败');
        }
      });
    },
    
    /** 导出按钮操作 */
    handleExport() {
      // 构建导出参数，使用与查询相同的筛选条件
      const params = {
        taskId: this.queryParams.taskId
      };
      
      // 添加筛选条件
      if (this.queryParams.userName) params.userName = this.queryParams.userName;
      if (this.queryParams.nickName) params.nickName = this.queryParams.nickName;
      if (this.queryParams.level) params.level = this.queryParams.level;
      if (this.queryParams.interviewer) params.interviewer = this.queryParams.interviewer;
      if (this.queryParams.interviewStatus) params.interviewStatus = this.queryParams.interviewStatus;
      if (this.queryParams.startTime) params.startTime = this.queryParams.startTime;
      if (this.queryParams.endTime) params.endTime = this.queryParams.endTime;
      
      this.$modal.confirm('是否确认导出访谈记录数据项？').then(() => {
        this.exportLoading = true;
        return exportInterview(params);
      }).then(response => {
        this.$download.excel(response, '访谈记录数据_' + new Date().getTime() + '.xlsx');
        this.exportLoading = false;
      }).catch(error => {
        if (error !== 'cancel') {
          console.error('导出访谈记录失败:', error);
          this.$message.error('导出访谈记录失败');
        }
        this.exportLoading = false;
      });
    },
    
    /** 表单重置 */
    reset() {
      this.form = {
        warnId: null,
        userName: null,
        nickName: null,
        level: null,
        interviewer: null,
        interviewTime: null,
        interviewResult: null
      };
      this.resetForm("form");
    },
    
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 修改访谈记录
            updateInterview(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('修改访谈记录失败:', error);
              this.$message.error('修改访谈记录失败');
            });
          } else {
            // 新增访谈记录
            addInterview(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('新增访谈记录失败:', error);
              this.$message.error('新增访谈记录失败');
            });
          }
        }
      });
    },
    
    /** 获取层级标签类型 */
    getLevelTagType(level) {
      switch (level) {
        case '1': return 'success';
        case '2': return 'warning';
        case '3': return 'danger';
        default: return 'info';
      }
    },
    
    /** 获取层级文本 */
    getLevelText(level) {
      switch (level) {
        case '1': return '一级';
        case '2': return '二级';
        case '3': return '三级';
        default: return level;
      }
    },
    
    /** 获取状态标签类型 */
    getStatusTagType(status) {
      switch (status) {
        case '1': return 'success';
        case '0': return 'info';
        default: return 'info';
      }
    },
    
    /** 获取状态文本 */
    getStatusText(status) {
      switch (status) {
        case '1': return '已访谈';
        case '0': return '未访谈';
        default: return '未访谈';
      }
    }
  }
};
</script>

<style scoped>
/* 整体容器 */
.app-container {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 84px);
}

/* 区域标题样式 */
.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e2e8f0;
  position: relative;
}

.section-header i {
  font-size: 18px;
  color: #409EFF;
  margin-right: 8px;
}

.section-header span {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  letter-spacing: 0.5px;
}

.section-header::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 60px;
  height: 2px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  border-radius: 1px;
}

/* 筛选容器 */
.filter-container {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  padding: 24px;
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  position: relative;
}

.filter-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #409EFF, #67C23A, #E6A23C, #F56C6C);
  border-radius: 12px 12px 0 0;
}

/* 表单项样式 */
.el-form-item {
  margin-bottom: 0;
}




/* 输入框和选择器样式 */
.el-input__inner,
.el-select .el-input__inner {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.el-input__inner:focus,
.el-select .el-input__inner:focus {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 级联选择器样式 */
.el-cascader {
  width: 100%;
}

.el-cascader .el-input__inner {
  border-radius: 8px;
}

/* 操作按钮样式 */
.action-buttons {
  margin-bottom: 20px;
}

.action-buttons .el-button {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  margin-right: 12px;
}

.action-buttons .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.action-buttons .el-button.el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.action-buttons .el-button.el-button--primary:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}



/* 标签样式优化 */
::v-deep .el-tag {
  border-radius: 6px;
  font-weight: 500;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

::v-deep .el-tag--success {
  background: linear-gradient(45deg, #67C23A, #85ce61);
  color: white;
}

::v-deep .el-tag--primary {
  background: linear-gradient(45deg, #409EFF, #36a3f7);
  color: white;
}

::v-deep .el-tag--warning {
  background: linear-gradient(45deg, #E6A23C, #ebb563);
  color: white;
}

::v-deep .el-tag--danger {
  background: linear-gradient(45deg, #F56C6C, #f78989);
  color: white;
}

::v-deep .el-tag--info {
  background: linear-gradient(45deg, #909399, #a6a9ad);
  color: white;
}

/* 分页样式优化 */
::v-deep .pagination-container {
  margin-top: 20px;
  text-align: center;
}

::v-deep .pagination-container .el-pagination .el-pager li,
::v-deep .pagination-container .el-pagination .btn-prev,
::v-deep .pagination-container .el-pagination .btn-next {
  border-radius: 6px;
  margin: 0 2px;
  transition: all 0.3s ease;
}

::v-deep .pagination-container .el-pagination .el-pager li:hover,
::v-deep .pagination-container .el-pagination .btn-prev:hover,
::v-deep .pagination-container .el-pagination .btn-next:hover {
  transform: translateY(-1px);
}

::v-deep .pagination-container .el-pagination .el-pager li.active {
  background: linear-gradient(45deg, #409EFF, #36a3f7);
  color: white;
}

/* 加载状态优化 */
::v-deep .el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(4px);
  border-radius: 12px;
}

/* 对话框样式优化 */
::v-deep .el-dialog {
  border-radius: 12px;
  overflow: hidden;
}

::v-deep .el-dialog .el-dialog__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
}

::v-deep .el-dialog .el-dialog__header .el-dialog__title {
  color: white;
  font-weight: 600;
}

::v-deep .el-dialog .el-dialog__header .el-dialog__close {
  color: white;
}

::v-deep .el-dialog .el-dialog__header .el-dialog__close:hover {
  color: #f0f0f0;
}

::v-deep .el-dialog .el-dialog__body {
  padding: 24px;
}

::v-deep .el-dialog .el-dialog__footer {
  padding: 16px 24px;
  background: #f8f9fa;
}

::v-deep .el-dialog .el-dialog__footer .el-button {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 16px;
  }
  
  .filter-container {
    padding: 16px;
  }
  
  .action-buttons {
    text-align: center;
  }
  
  .action-buttons .el-button {
    margin: 4px;
    font-size: 12px;
    padding: 8px 16px;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.filter-container {
  animation: fadeInUp 0.6s ease-out;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(45deg, #409EFF, #36a3f7);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(45deg, #36a3f7, #409EFF);
}
</style>